import Pubsub from 'pubsub-js';

export default {
  mappingModalShow(state, {flag}) {
    state.mappingModalShow = flag;
    state.singleTable = {};
  },
  singleTableMappingModalShow(state, {flag}) {
    state.singleTableMappingModalShow = flag;
  },
  chooseSettingModalShow(state, {flag}) {
    try {
      let linkkId = state.currentLinkInfo.id;
      let data = webEngine.invoke1("/loadSettings", linkkId);
      state.settings = JSON.parse(data);
    } catch (e) {
      console.error(e);
      if (state.environment === "dev") {
        state.settings = [
          {name: "配置1", id: 1},
          {name: "配置2", id: 2},
          {name: "配置3", id: 3}
        ];
      }
    }
    state.chooseSettingModalShow = flag;
  },
  editLinkModalShow(state, {flag}) {
    state.editLinkModalShow = flag;
  },
  deleteLinkModalShow(state, {flag}) {
    state.deleteLinkModalShow = flag;
  },
  createLinkModalShow(state, {flag}) {
    let json = JSON.stringify(state.defaultLinkInfo);
    state.newLinkInfo = JSON.parse(json);
    state.createLinkModalShow = flag;
  },
  saveSettingModalShow(state, {flag}) {
    let data = JSON.stringify(state.currentLinkInfo);
    if ("{}" === data) {
      state.saveSettingModalShow = false;
      return;
    }
    state.saveSettingModalShow = flag;
  },
  infoModalShow(state, {flag}) {
    state.infoModalShow = flag;
  },
  setCurrentLinkInfo(state, {linkInfo}) {
    state.currentLinkInfo = linkInfo;
    state.currentLinkInfoCopy = JSON.parse(JSON.stringify(linkInfo));
  },
  setCurrentDatabase(state, {database}) {
    state.currentDatabase = database;
  },
  checkAll(state, {database}) {
    database.tables.forEach(table => {
      table.checked = database.checked;
    })
    /* state.linkInfos.forEach(linkInfo => {
       linkInfo.databases.forEach(db => {
         if (database === db) {
           db.tables.forEach(table => {
             table.checked = db.checked;
           })
         }
       })
     });*/
  },
  cancelCheckAll(state) {
    state.linkInfos.forEach(linkInfo => {
      if (linkInfo.databases) {
        linkInfo.databases.forEach(db => {
          db.checked = false;
          db.tables.forEach(table => {
            table.checked = false;
          })
        })
      }
    })
  }

  , loadLinks(state) {
    console.log("加载环境变量")
    setTimeout(() => {
      try {
        state.environment = window.webEngine.invoke0("/loadEnvironmentInfo");
        if (state.environment !== "dev") {
          state.projectSetting.projectPackage = "";
          state.projectSetting.codePath = "";
        }
        let json = window.webEngine.invoke0("/loadLinks");
        let linkInfos = JSON.parse(json);
        linkInfos.forEach(linkInfo => linkInfo.databases = []);
        state.linkInfos = linkInfos;
      } catch (e) {
        window.app.$message({
          message: "加载连接失败!",
          type: "warning"
        });
        console.log(e);
        if (state.environment === "dev") {
          state.linkInfos = [
            {
              id: 1,
              name: "mysql",
              user: "root",
              password: "root",
              host: "127.0.0.1",
              port: "3306",
              databaseType: "mysql",
              databases: []
            },
            {
              id: 2,
              name: "mariadb",
              user: "root",
              password: "root",
              host: "127.0.0.1",
              port: "4306",
              databaseType: "mariadb",
              databases: []
            },
            {
              id: 3,
              name: "oracle",
              user: "scott",
              password: "TIGGER",
              host: "192.168.31.211",
              port: "1521",
              databaseType: "oracle",
              databases: []
            },
            {
              id: 3,
              name: "sqlServer",
              user: "root",
              password: "root",
              host: "192.168.31.109",
              port: "1433",
              databaseType: "sqlserver",
              databases: []
            },
          ];
        }
      }
    }, 500)

  },
  loadDatabases(state, {linkInfo}) {
    try {
      let json = window.webEngine.invoke1("/loadDatabases", JSON.stringify(linkInfo));
      linkInfo.databases = JSON.parse(json);
      state.linkIsOpen = true;
    } catch (e) {
      Pubsub.publish("loadDatabases");
      console.log(e);
      if (state.environment === "dev") {
        state.linkIsOpen = true;
        linkInfo.databases = [
          {
            name: "mysql",
            checked: false,
            tables: [
              {name: "t_user", checked: false},
              {name: "t_order", checked: false}
            ]
          },
          {
            name: "test",
            checked: false,
            tables: [
              {name: "cfg_operation", checked: false},
              {name: "t_menu", checked: false}
            ]
          }
        ];
      }
    }
  },
  updateLink(state) {
    let linkInfoString = JSON.stringify(state.currentLinkInfoCopy);
    try {
      //提交副本数据
      webEngine.invoke1("/updateLink", linkInfoString);
      window.app.$message({
        message: "修改连接成功!",
        type: "success"
      });
    } catch (e) {
      window.app.$message({
        message: "修改连接失败!",
        type: "warning"
      });
      console.error(e);
    }
    //操作完成后再赋值给原数据
    state.currentLinkInfo.name = state.currentLinkInfoCopy.name;

  },
  saveLink(state) {
    let linkInfoString = JSON.stringify(state.newLinkInfo);
    try {
      linkInfoString = webEngine.invoke1("/saveLink", linkInfoString);
      window.app.$message({
        message: "保存连接成功!",
        type: "success"
      });
    } catch (e) {
      window.app.$message({
        message: "保存连接失败!",
        type: "warning"
      });
      console.error(e);
    }
    let linkInfo = JSON.parse(linkInfoString);
    linkInfo.databases = [];
    state.linkInfos.splice(state.linkInfos.length, 0, linkInfo);
  },
  deleteLink(state) {
    let id = state.currentLinkInfo.id;
    try {
      webEngine.invoke1("/deleteLink", id + "");
      window.app.$message({
        message: "删除连接成功!",
        type: "success"
      });
    } catch (e) {
      window.app.$message({
        message: "删除连接失败!",
        type: "warning"
      });
      console.error(e);
    }
    let index = -1;
    for (let i = 0; i < state.linkInfos.length; i++) {
      if (state.currentLinkInfo === state.linkInfos[i]) {
        index = i;
        break;
      }
    }
    if (index !== -1) {
      state.linkInfos.splice(index, 1);
    }
    state.currentLinkInfo = {};
  },
  loadSettingDetail(state, {settingId}) {
    try {
      let data = webEngine.invoke1("/loadSettingDetail", settingId + "");
      data = JSON.parse(data);
      state.projectSetting = data.project;
      state.entitySetting = data.entity;
      state.mapperSetting = data.mapper;
      state.repositorySetting = data.repository;
      state.serviceSetting = data.service;
      state.controllerSetting = data.controller;
      window.app.$message({
        message: "加载配置成功!",
        type: "success"
      });
    } catch (e) {
      window.app.$message({
        message: "加载配置失败!",
        type: "warning"
      });
      console.error(e);
    }
  },
  saveSettings(state, {name}) {
    try {
      let settings = {
        project: state.projectSetting,
        entity: state.entitySetting,
        mapper: state.mapperSetting,
        repository: state.repositorySetting,
        service: state.serviceSetting,
        controller: state.controllerSetting
      };
      let settingsInfo = {
        linkId: state.currentLinkInfo.id,
        name: name,
        settings: settings,
        dbType: state.currentLinkInfo.databaseType
      };
      webEngine.invoke1("/saveSettings", JSON.stringify(settingsInfo));
      window.app.$message({
        message: "保存配置成功!",
        type: "success"
      });
    } catch (e) {
      console.error(e);
      window.app.$message({
        message: "保存配置失败!",
        type: "warning"
      });
    }
  },
  generateCode(state, {databases}) {
    state.generating = true;
    let flag = true;
    state.generating = true;
    try {
      state.entitySetting.mapping = state.customeMapping;
      let request = {
        id: state.currentLinkInfo.id,
        settings: {
          project: state.projectSetting,
          entity: state.entitySetting,
          mapper: state.mapperSetting,
          repository: state.repositorySetting,
          service: state.serviceSetting,
          controller: state.controllerSetting,
        },
        databases:databases
      };

      let singleTableMappingString = "";
      if (window.isSingleTable(state.currentLinkInfo)) {
        singleTableMappingString = JSON.stringify(state.singleTableMappings);
      }
      console.log(JSON.stringify(request));
      webEngine.invoke2("/generateCode", JSON.stringify(request), singleTableMappingString);
    } catch (e) {
      console.error(e);
      flag = false;

    }
    state.generating = false;

    Pubsub.publish("generating", false);
    setTimeout(() => {
      if (flag) {
        window.app.$message({
          message: '代码生成完成!',
          type: 'success'
        });
      } else {
        window.app.$message({
          message: '代码生成失败!',
          type: 'warning'
        });
      }
    }, 500);
  },
  loadMappings(state, {settingId}) {
    let javaTypes = ["java.lang.String", "java.lang.Long", "java.lang.Integer"];
    let mappingSettings = JSON.parse('[{"columnType":"int","columnTypeId":1,"fullName":"java.lang.Integer","javaTypeId":3},{"columnType":"tinyint","columnTypeId":2,"fullName":"java.lang.Integer","javaTypeId":3},{"columnType":"smallint","columnTypeId":3,"fullName":"java.lang.Integer","javaTypeId":3},{"columnType":"mediumint","columnTypeId":4,"fullName":"java.lang.Integer","javaTypeId":3},{"columnType":"integer","columnTypeId":5,"fullName":"java.lang.Integer","javaTypeId":3},{"columnType":"bigint","columnTypeId":6,"fullName":"java.lang.Long","javaTypeId":2},{"columnType":"float","columnTypeId":7,"fullName":"java.lang.Float","javaTypeId":16},{"columnType":"double","columnTypeId":8,"fullName":"java.lang.Double","javaTypeId":17},{"columnType":"varchar","columnTypeId":10,"fullName":"java.lang.String","javaTypeId":1},{"columnType":"tinyblob","columnTypeId":11,"fullName":"java.sql.Blob","javaTypeId":9},{"columnType":"tinytext","columnTypeId":12,"fullName":"java.lang.String","javaTypeId":1},{"columnType":"blob","columnTypeId":13,"fullName":"java.sql.Blob","javaTypeId":9},{"columnType":"text","columnTypeId":14,"fullName":"java.lang.String","javaTypeId":1},{"columnType":"mediumblob","columnTypeId":15,"fullName":"java.sql.Blob","javaTypeId":9},{"columnType":"mediumtext","columnTypeId":16,"fullName":"java.lang.String","javaTypeId":1},{"columnType":"longblob","columnTypeId":17,"fullName":"java.sql.Blob","javaTypeId":9},{"columnType":"longtext","columnTypeId":18,"fullName":"java.lang.String","javaTypeId":1},{"columnType":"date","columnTypeId":19,"fullName":"java.time.LocalDate","javaTypeId":12},{"columnType":"time","columnTypeId":20,"fullName":"java.time.LocalTime","javaTypeId":14}]');
    try {
      let linkInfo = JSON.stringify(state.currentLinkInfo);
      let data = webEngine.invoke2("/loadMappings", linkInfo, settingId);
      let json = JSON.parse(data);
      javaTypes = json.javaTypes;
      mappingSettings = json.mappingSettings;
    } catch (e) {
      window.app.$message({
        message: "加载映射失败!",
        type: "warning"
      });
      console.error(e);
    }
    state.javaTypes = javaTypes;
    state.mappingSettings = mappingSettings;
  },
  customeMapping(state, {mapping}) {
    state.customeMapping = mapping;
  },
  loadSingleTableMapping(state, {tableInfo}) {
    if ("{}" === JSON.stringify(state.singleTable)
      ||state.singleTable.database !==tableInfo.database
      ||state.singleTable.table !==tableInfo.table) {

      state.singleTable = tableInfo;
      try {
        let data = webEngine.invoke4("/loadSingleTableMapping",
          state.entitySetting.primaryKeyName,
          tableInfo.database, tableInfo.table,
          JSON.stringify(state.currentLinkInfo));
        state.singleTableMapping = JSON.parse(data);
      } catch (e) {
        console.log(e);
        if (state.environment === "dev") {
          let data = '{"javaTypes":[{"fullName":"java.lang.String","id":1,"needImport":false,"shortName":"String"},{"fullName":"java.lang.Long","id":2,"needImport":false,"shortName":"Long"},{"fullName":"java.lang.Integer","id":3,"needImport":false,"shortName":"Integer"},{"fullName":"java.lang.Boolean","id":4,"needImport":false,"shortName":"Boolean"},{"fullName":"java.lang.Byte","id":5,"needImport":false,"shortName":"Byte"},{"fullName":"java.util.Date","id":6,"needImport":true,"shortName":"Date"},{"fullName":"java.sql.Date","id":7,"needImport":true,"shortName":"Date"},{"fullName":"java.sql.Timestamp","id":8,"needImport":true,"shortName":"Timestamp"},{"fullName":"java.sql.Blob","id":9,"needImport":true,"shortName":"Blob"},{"fullName":"java.math.BigDecimal","id":10,"needImport":true,"shortName":"BigDecimal"},{"fullName":"java.math.BigInteger","id":11,"needImport":true,"shortName":"BigInteger"},{"fullName":"java.time.LocalDate","id":12,"needImport":true,"shortName":"LocalDate"},{"fullName":"java.time.LocalDateTime","id":13,"needImport":true,"shortName":"LocalDateTime"},{"fullName":"java.time.LocalTime","id":14,"needImport":true,"shortName":"LocalTime"},{"fullName":"java.lang.Short","id":15,"needImport":false,"shortName":"Short"},{"fullName":"java.lang.Float","id":16,"needImport":false,"shortName":"Float"},{"fullName":"java.lang.Double","id":17,"needImport":false,"shortName":"Double"},{"fullName":"java.lang.Character","id":18,"needImport":false,"shortName":"Character"},{"fullName":"java.sql.Clob","id":19,"needImport":true,"shortName":"Clob"},{"fullName":"byte[]","id":21,"needImport":false,"shortName":"byte[]"}],"mappings":[{"columnName":"id","columnType":"int","javaType":{"fullName":"java.lang.Integer","needImport":false,"shortName":"Integer"}},{"columnName":"password","columnType":"varchar","javaType":{"fullName":"java.lang.String","needImport":false,"shortName":"String"}},{"columnName":"createTime","columnType":"datetime","javaType":{"fullName":"java.time.LocalDateTime","needImport":true,"shortName":"LocalDateTime"}},{"columnName":"username","columnType":"varchar","javaType":{"fullName":"java.lang.String","needImport":false,"shortName":"String"}},{"columnName":"birthday","columnType":"datetime","javaType":{"fullName":"java.time.LocalDateTime","needImport":true,"shortName":"LocalDateTime"}}]}';
          state.singleTableMapping = JSON.parse(data);
        }
        window.app.$message({
          message: "加载映射失败!",
          type: "warning"
        });
      }

    }
  },
  setSingleTableMapping(state, {singleTableMappings}) {
    this.state.singleTableMappings = singleTableMappings;
  },
  openCodeFolder(state) {
    webEngine.invoke1("/openCodeFolder", state.projectSetting.codePath);
  }
}
